package com.jacen.fzxs.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jodd.util.StringUtil;

public class HttpUtil {
	
	public static String METHOD_POST ="POST";
	public static String METHOD_GET ="GET";
	/**
	 * 发生http请求
	 * @param method get/post
	 * @param urlStr 请求地址
	 * @return
	 */
	public static String sendRequest(String method,String urlStr) throws Exception{
    	URL url = new URL(urlStr);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setUseCaches(false);
		conn.setRequestMethod(method);
		conn.setRequestProperty("connection", "Keep-Alive");
		conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
		conn.setRequestProperty("Charsert", "UTF-8");
		// 设置发送类型，以防被struts拦截参数
		conn.setRequestProperty("Content-Type", "text/html");
		// 定义BufferedReader输入流来读取URL的响应
		BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
		String line = null;
		StringBuffer sb = new StringBuffer();
		while ((line = reader.readLine()) != null) {
			sb.append(new String(line.getBytes("UTF-8")));
		}
    	return sb.toString();
	}
	
	public static String readFromRequest(HttpServletRequest request) throws IOException {
		InputStream is = request.getInputStream();
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		int bufSize = 4096;
		byte[] buff = new byte[bufSize];
		int len = bufSize;
		while ((len = is.read(buff, 0, len)) != -1) {
			os.write(buff, 0, len);
		}
		return new String(os.toByteArray(), "UTF-8");
	}
	
	public static void writeToResponse(HttpServletResponse response, String data, String characterEncoding) {
		if (!StringUtil.isEmpty(characterEncoding)) {
			response.setCharacterEncoding(characterEncoding);
		}
		PrintWriter pw = null;
		try {
			pw = response.getWriter();
			pw.print(data);
			pw.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (pw != null) {
				pw.close();
			}
		}
	}

}
